#!/usr/bin/python
# vim:fileencoding=utf8
"""
Обеспечивает ввод-вывод.
"""

from xml.etree import ElementTree

from aiexception import AIException
from words import article, noun, verb
                  
def load_dictionary(file_name, map_of_dictionaries):
    #TODO тестирование ненормального поведения
    tree = ElementTree.parse(file_name)
    for word_element in tree.getroot():
        if word_element.tag != 'word':
            raise AIException(
                    'Unexpected tag %s in dictionry file' % word_element.tag
                    )
        else:
            load_word(word_element, map_of_dictionaries)


        
def load_word(word_element, map_of_dictionaries):
    base = None
    noun_dictionary = map_of_dictionaries.get('noun', {})
    verb_dictionary = map_of_dictionaries.get('verb', {})
    for subnode in word_element:
        if subnode.tag == 'base':
            base = subnode.text
        elif subnode.tag == 'noun':
            process_noun(base, subnode, noun_dictionary)
        elif subnode.tag == 'verb':
            process_verb(base, subnode, verb_dictionary)
        else:
            raise AIException(
                    'Unexpected word type %s' % subnode.tag
                    )

def process_noun(base, node, dictionary):
    assert node.tag == 'noun'
    dictionary_append(dictionary, base, noun.Noun(base))
    dictionary[base] = noun.Noun(base)

def process_verb(base, node, dictionary):
    assert node.tag == 'verb'
#    dictionary_append(dictionary, base, noun.Noun(base))   
    dictionary[base] = verb.Verb(base)


def dictionary_append(dictionary, key, value):
    if key in dictionary:
        dictionary[key].append(value)
    else:
        dictionary[key] = [value]
    
if __name__ == "__main__":
    res = {'noun':{}, 'verb':{}}
    load_dictionary("../../data/words.xml", res)
    print res
